package com.tanhua.app.interceptor;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        //1.判断token是否合法
        boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //2.如果token可用放行,获取手机号和id
        Claims claims = JwtUtils.getClaims(token);
        String mobile = (String) claims.get("mobile").toString();
        Long id = Long.parseLong(claims.get("id").toString());

        User user = new User();
        user.setMobile(mobile);
        user.setId(id);
        //将用户数据放到threadLocal中
        UserHolder.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
